﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using System.Collections.Generic;
using AAEngine.Engine;
using AAEngine.Engine.Debug;
using AAEngine.Engine.Entities;
using AAEngine.Rendering2D.Renderers;

namespace AAEngine.Rendering2D
{
    public class BasicScene2D : EntityComponent, IScene2D
    {
        private List<ISceneLayer> _layers = new List<ISceneLayer>();

        public int LayerCount { get { return _layers.Count; } }

#if WINDOWS_PHONE || XBOX
        public ISceneLayer GetLayer(int index)
        {
            return GetLayer(index, false);
        }

        public ISceneLayer GetLayer(int index, bool allocateIfAbsent)
#else
        public ISceneLayer GetLayer(int index, bool allocateIfAbsent = false)
#endif
        {
            ValidateListSize(index);

            if(_layers[index] != null)
            {
                return _layers[index];
            }

            if (allocateIfAbsent == false)
            {
                return null;
            }

            _layers[index] = new SceneLayer();

            return _layers[index];
        }

        public void AddRenderable(RendererBase renderableObject)
        {
            GetLayer(renderableObject.LayerIndex, true).Add(renderableObject);
        }

        public void RemoveRenderable(RendererBase renderableObject)
        {
            GetLayer(renderableObject.LayerIndex, true).Remove(renderableObject);
        }

        public void RenderScene(Box worldExtents, RenderQueue renderQueue)
        {
            Profiler.Enter("BasicScene2D::RenderScene");
            for(int i = 0; i < _layers.Count; i++)
            {
                if (_layers[i] != null)
                {
                    renderQueue.StartLayer();
                    _layers[i].RenderLayer(worldExtents, renderQueue);
                    renderQueue.EndLayer();
                }
            }
            Profiler.Exit("BasicScene2D::RenderScene");
        }

        private void ValidateListSize(int index)
        {
            if (_layers.Count <= index)
            {
                _layers.AddRange(new ISceneLayer[index - _layers.Count + 1]); 
            }
        }
    }
}
